import { login, getAvatar } from '@/api'

const state = {
  token: localStorage.getItem('token') | '',
  userInfo: JSON.parse(localStorage.getItem('userInfo')),
  avatar: JSON.parse(localStorage.getItem('avatar')),
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  setAvatar: (state, avatar) => {
    state.avatar = avatar
  },
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((res) => {
          if (res.code == 200) {
            console.log('res', res)
            userInfo.name = res.data.employeeName
            userInfo.positionName = res.data.positionName
            userInfo.userId = res.data.userId
            userInfo.gender = res.data.gender
            commit('setUserInfo', userInfo)
            commit('SET_TOKEN', res.data.accessToken)
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
            localStorage.setItem('token', res.data.accessToken)
            resolve()
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  setAvatar({ commit }) {
    return new Promise((resolve, reject) => {
      getAvatar('token')
        .then((res) => {
          const avatar = res
          commit('setAvatar', avatar)
          localStorage.setItem('avatar', JSON.stringify(state.avatar))
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('setRoutes', '')
      commit('setButtons', '')
      commit('setUserInfo', '')
      commit('setAvatar', '')
      localStorage.removeItem('token')
      localStorage.removeItem('buttons')
      localStorage.removeItem('avatar')
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
